<?php
declare (strict_types = 1);

namespace app\controller\backend;

use app\model\Admin;
use app\model\AdminMenu;
use app\validate\AdminValidate;
use think\exception\ValidateException;
use think\facade\Db;

class AdminController extends BaseController
{

    /**
     * @param Admin $admin
     * @return \think\response\Json
     * @throws \app\exception\ModelException
     */
    public function index(Admin $admin): \think\response\Json
    {
        $where = [
            'seller_id' => $this->admin['seller_id'],
            'is_del' => 1,
        ];
        $limit = $this->setLimit();
        $adminList = $admin->getAdminList($where,$limit);
        return json(pageReturn($adminList));
    }

    /**
     * @throws \app\exception\ModelEmptyException
     * @throws \app\exception\ModelException
     */
    public function read(Admin $Admin): \think\response\Json
    {
        $id = (int)input('id');
        if(!$id){
            return jsonReturn(-1,'管理员ID不能为空');
        }
        $where = [
            'id' => $id,
            'seller_id' => $this->admin['seller_id']
        ];
        $res = $Admin->getAdmin($where,['role']);
        return json($res);
    }

    /**
     * 新建管理员
     *
     * @param Admin $admin
     * @return \think\Response
     * @throws \app\exception\ModelException
     */
    public function save(Admin $admin): \think\Response
    {
        $param = input('post.');
        try{
            validate(AdminValidate::class)->scene('save')->check($param);
        }catch(ValidateException $e){
            return jsonReturn(-1, $e->getError());
        }
        $param['password'] = makePassword($param['password']);
        if(isset($param['group'])){
            unset($param);
        }
        Db::startTrans();
        try{
            $res = $admin -> addAdmin($param);
            $res['data']->role()->attach($param['role'],['seller_id'=>$this->admin['seller_id']]);
            event("AdminOptLog",[
                'admin_id' => $this->admin['uid'],
                'admin_name' => $this->admin['name'],
                'title'=>"管理员管理",
                "content"=>"新增管理员".$res['data']['id'],
            ]);
            Db::commit();
        }catch (\Exception $e){
            Db::rollback();
            return jsonReturn(-3,$e->getMessage());
        }

        return json($res);
    }

    /**
     * 编辑管理员
     * @return \think\response\Json
     * @throws \app\exception\ModelException
     */
    public function update(Admin $admin): \think\response\Json
    {
        if(request()->isPost()){
            $param = request()->except(['password']);
            try {
                validate(AdminValidate::class)->scene('update')->check($param);
            } catch (ValidateException $e) {
                return jsonReturn(-1, $e->getError());
            }
            $where = [
                'id' => $param['id'],
                'seller_id' => $this->admin['seller_id'],
                'is_del' => 1,
            ];
            Db::startTrans();
            try{
                if(isset($param['group'])){
                    unset($param);
                }
                $manager = $admin -> getAdmin($where)['data'];
                $manager->role()->detach();
                $manager->role()->attach($param['role'],['seller_id'=>$this->admin['seller_id']]);
                if(!empty($param['password'])){
                    $param['password'] = makePassword($param['password']);
                }
                unset($param['role']);
                $res = $admin->updateAdmin($where,$param);
                event("AdminOptLog",[
                    'admin_id' => $this->admin['uid'],
                    'admin_name' => $this->admin['name'],
                    'title'=>"管理员管理",
                    "content"=>"更新管理员信息".$param['id'],
                ]);
                Db::commit();
            }catch (\Exception $e){
                Db::rollback();
                return jsonReturn(-3,$e->getMessage());
            }
            return json($res);
        }
        return jsonReturn(-3,'请求方法错误');
    }

    /**
     * 删除管理员
     *
     * @throws \app\exception\ModelException
     */
    public function delete(Admin $admin): \think\response\Json
    {
        if(request()->isPost()){
            $id = (int)input('id');
            if(!$id){
                return jsonReturn(-1,'管理员ID不能为空');
            }
            $where = [
                'id' => $id,
                'seller_id' => $this->admin['seller_id']
            ];
            event("AdminOptLog",[
                'admin_id' => $this->admin['uid'],
                'admin_name' => $this->admin['name'],
                'title'=>"管理员管理",
                "content"=>"删除管理员".$id,
            ]);
            $res = $admin->delAdmin($where);
            return json($res);
        }
        return jsonReturn(-3,'请求方法错误');
    }

    /**
     * 重置管理员密码
     *
     * @throws \app\exception\ModelException
     */
    public function resetPass(Admin $admin): \think\response\Json
    {
        if(request()->isPost()){
            $param = input('post.');
            try {
                validate(AdminValidate::class)->scene('resetPass')->check($param);
            } catch (ValidateException $e) {
                return jsonReturn(-1, $e->getError());
            }
            $where = [
                'id' => $param['id'],
                'seller_id' => $this->admin['seller_id'],
            ];
            $res = $admin -> updateAdmin($where,$param);
            return json($res);
        }
        return jsonReturn(-3,'请求方法错误');
    }

    /**
     * @throws \app\exception\ModelException
     * @throws \app\exception\ModelEmptyException
     */
    public function self(Admin $Admin,AdminMenu $AdminMenu): \think\response\Json
    {
        $admin = $Admin->getAdmin(['id' => $this->admin['uid'],'seller_id' => $this->admin['seller_id']],['role'])['data'];
        // 获取权限
        $role = $admin['role']->toArray();

        if(empty($role)){
            $menu = $AdminMenu->getAllAdminMenu(['is_menu'=>1,'seller_id'=>$admin['seller_id']])['data']->toArray();
        }else{
            if($admin['group'] == 1){
                $auth = $AdminMenu->getAllAdminMenu(['seller_id'=>1])['data']->toArray();
            }else{
                $menuIds = array_column($role,'auth');
                $whereIn = array_unique($menuIds);
                $auth = $AdminMenu -> getAllAdminMenu(['id','in',$whereIn])['data']->toArray();
            }
            $menu = [];
            foreach ($auth as $val){
                if($val['is_menu'] == 1){
                    array_push($menu,$val);
                }
            }
        }
        $menu = makeTree($menu);
        return jsonReturn(0,'success',[
            'user' => $admin,
            'menu' => $menu,
        ]);
    }
}
